package com.gzu.ltms.service.impl;

import com.gzu.ltms.config.EmailConfig;
import com.gzu.ltms.constant.RedisKeyConstants;
import com.gzu.ltms.entity.vo.SendVerificationCodeReqVO;
import com.gzu.ltms.enums.ResponseCodeEnum;
import com.gzu.ltms.exception.BizException;
import com.gzu.ltms.response.Response;
import com.gzu.ltms.service.VerificationCodeService;
import com.gzu.ltms.uitl.JsonUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private EmailConfig emailConfig;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        // 手机号
        String phone = sendVerificationCodeReqVO.getPhone();

        // 构建验证码 redis key
        String key = RedisKeyConstants.buildVerificationCodeKey(phone);

        // 判断是否已发送验证码
        boolean isSent = redisTemplate.hasKey(key);
        if (isSent) {
            // 若之前发送的验证码未过期，则提示发送频繁
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }

        // 准备发送消息
        // 构建消息体
        Message<String> message = MessageBuilder.withPayload(JsonUtils.toJsonString(sendVerificationCodeReqVO))
                .build();

        String destination = "send:phone";
        String hashKey = phone;
        // 异步发送
        rocketMQTemplate.asyncSendOrderly(destination, message, hashKey, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("==> MQ发送成功：{}", sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("==> MQ发送失败: ", throwable);
            }
        });

        return Response.success();
    }


    /**
     * 发送邮箱验证码
     * @param email
     * @return
     */
    @Override
    public Response<?> email(String email) {
        emailConfig.sendEmail(email);
        return Response.success();
    }
}
